<?php
namespace Common\Org\Util;
use Common\Org\Curl\Curl;

/*
 * 高德LBS开放平台
 * API参考手册： http://lbs.amap.com/yuntu/reference/cloudstorage/
 */

class GaodeAmapLbs {

    private $_tableId;
    private $_cloudKey;
    private $_curl;
    const GAODE_CLOUD_KEY = 'e58bae199679e49544969133bc20896e';     //高德云图KEY
    CONST YUNTU_TABLE_ID = "53eb010ce4b0f5e323e5ffad";
    const YUNTU_MANAGE  = 'http://yuntuapi.amap.com/datamanage/data/'; //云图数据管理接口地址
    const YUNTU_SEARCH  = 'http://yuntuapi.amap.com/datamanage/data/list?'; //云图数据查询接口地址
    CONST REST_API_HOST = "http://restapi.amap.com/v3";
    const REST_API_CONVERT = "/assistant/coordinate/convert";  //经纬度转换
    const REQUEST_PARAMS_NULL = "请提供完整的参数";
        
    public function __construct($cloud_key = '', $table_id = '') {
        $this->_cloudKey = !empty($cloud_key) ? $cloud_key : self::GAODE_CLOUD_KEY;
        $this->_tableId = !empty($table_id) ? $table_id : self::YUNTU_TABLE_ID;
        $this->_curl = new Curl();
    }

    public function setCloudKey($key) {
        $this->_cloudKey = $key;
    }

    public function setTableId($id) {
        $this->_tableId = $id;
    }

    public function getCloudKey() {
        return $this->_cloudKey;
    }

    public function getTableId() {
        return $this->_tableId;
    }

    /**
     * 为高德云图table中新增一条记录
     * @param string $name          数据名称
     * @param string $location      坐标示例：104.394729,31.125698
     * @param string $address       地址
     * @param array $custom         用户自定义字段数组
     * @param integer $loctype      默认：1; 1-经纬度，2-高德根据地址自动转换经纬度
     * @return array ["info":"成功或失败信息", "status"：1-成功;0-失败, "_id":"返回ID"]
     */
    public function create($name, $location, $address, $custom = [], $loctype = 1) {
        $url = self::YUNTU_MANAGE . 'create';

        if (empty($name) || empty($location) || empty($address))
            return ["info" => self::REQUEST_PARAMS_NULL, "status" => 0];

        $data = [
            '_name'     => $name,
            '_location' => $location,
            '_address'  => $address
        ];
        if (!empty($custom))
            $data = array_merge($data, $custom);

        $postData = [
            'key'     => $this->_cloudKey,
            'tableid' => $this->_tableId,
            'loctype' => $loctype,
            'data'    => json_encode($data)
        ];
        $response = $this->_curl->post($url, $postData);
        return self::object2array($response);
    }

    /**
     * 更新高德云图table中的一条记录
     * @param array $data  固定字段+用户自定义字段的数组：
     *             固定字段：
     *                  _id         =>  主键                              //必填
     *                  _name       =>  数据名称(门店名称)                  //可选
     *                  _location   => 坐标示例：104.394729,31.125698        //可选
     *                  _address    => 地址                               //可选
     * @param integer $loctype     默认：1; 1-经纬度，2-高德根据地址自动转换经纬度
     * @return array    ["info":"成功或失败信息", "status"：1-成功;0-失败, "_id":"返回ID"]
     */
    public function update($data, $loctype = 1) {
        $url = self::YUNTU_MANAGE . 'update';
        $data = (array) $data;
        if (!array_key_exists('_id', $data) || intval($data['_id']) == 0)
            return ["info" => self::REQUEST_PARAMS_NULL, "status" => 0];

        $postData = [
            'key'     => $this->_cloudKey,
            'tableid' => $this->_tableId,
            'loctype' => $loctype,
            'data'    => json_encode($data)
        ];
        $response = $this->_curl->post($url, $postData);
        return self::object2array($response);
    }

    /**
     * 删除高德云图table中的一条记录
     * @param string $ids 删除的数据_id: 一次请求限制1-50条数据，多个_id用逗号隔开
     * @return array    ["info":"成功或失败信息", "status"：1-成功;0-失败, "_id":"返回ID"]
     */
    public function remove($ids) {
        $url = self::YUNTU_MANAGE . 'delete';
        if (strlen($ids) <= 0)
            return ["info" => self::REQUEST_PARAMS_NULL, "status" => 0];

        $postData = [
            'key'     => $this->_cloudKey,
            'tableid' => $this->_tableId,
            'ids'     => $ids
        ];
        $response = $this->_curl->post($url, $postData);
        return self::object2array($response);
    }

    /**
     * 根据ID检索高德云图中的一条数据
     * @param integer $id  主键数据_id
     * @return array    具体返回数据格式请参考输出返回值
     */
    public function getById($id) {
        $url = self::YUNTU_SEARCH . "id";
        if (intval($id) <= 0)
            return ["info" => self::REQUEST_PARAMS_NULL, "status" => 0];

        $postData = [
            'tableid' => $this->_tableId,
            'key'     => $this->_cloudKey,
            '_id'     => $id
        ];

        $response = $this->_curl->post($url, $postData);
        return self::object2array($response);
    }
    
    /**
     * 转换为高德坐标 - 支持批量转换,最多1000
     * @param string $data    	坐标点：array("经度,纬度","经度,纬度")
     * @param string $coordsys    原坐标系：可选值(gps;mapbar;baidu)
     * @return array
     */
    public function convertLatLng($data, $coordsys="gps") {
        if (empty($data) || !is_array($data)) {
            return false;
        }
        $locations = implode(";", $data);
        $parameters = [
                "key"       => $this->_cloudKey,
                "locations" => $locations,
                "coordsys"  => $coordsys,
                "output"    => "json"
            ];
        $sendUrl = self::REST_API_HOST . self::REST_API_CONVERT ;
        $response = $this->_curl->get($sendUrl, $parameters);
        if (intval($response->status) !== 1)
            return ["status"=>1,"info"=>$response->info,"data"=>[]];
        
        $responseLocations = explode(";", $response->locations);
        return ["status"=>0,"info"=>$response->info,"data"=>$responseLocations];
    }

    /**
     * stdClass Object TO array
     * @param object|array $object
     * @return array
     */
    static private function object2array($object) {
        $array = [];
        if(is_object($object)) {
            try {
                $array = (array) $object;
            } catch(\Exception $e) {
                if (is_object($object)) {
                    foreach ($object as $key => $value) {
                        $array[$key] = $value;
                    }
                }
            }
        } if(is_array($object)) {
            foreach($object as $key=>$value) {
                $array[$key] = self::object2array($value);
            }
        }
        return $array;
    }

    /**
     * array TO stdClass Object
     * @param object|array $array
     * @return object
     */
    static private function array2object($array) {
        if (is_array($array)) {
            $object = new \StdClass();
            foreach ($array as $key=>$value){
                $object->$key = $value;
            }
        }
        else {
            $object = $array;
        }
        return $object;
    }

}
